# coding=utf-8
# need to install
# pip install flask
# flask
from flask import Flask
from flask import request
import json
import os
app = Flask(__name__)

customMap = {}
customMapHigh = {}


@app.route("/")
def hello():
    return "淦蛤呢"


@app.route("/custom-map/", methods=['GET', 'POST'])
def getCustomMap():
    data = customMap
    return data

@app.route("/custom-map-high/", methods=['GET', 'POST'])
def getCustomMapHigh():
    data = customMapHigh
    return data

@app.route("/custom-map-refresh/", methods=['GET', 'POST'])
def refreshMap():
    data = request.get_json()
    password = data['password']
    print(data)
    data = {
        'flag' : False,
        'data': "no data"
    }
    if password == "luigi1998":
        data['flag'] = True
        result = os.system("python3 custom-map.py")
        initCustomMap()
        initHighlightedMap()
        data['data'] = result
    return data


def initCustomMap():
    try:
        f = open('./custom-map-result.json', 'r')
        data = ""
        lines = f.readlines()
        for line in lines:
            data += line
        global customMap
        customMap = json.dumps(json.loads(data))

        print('\033[1;32m Success: 已加载custom-map-result.json! \033[0m')
    except IOError:
        print('\033[1;31m Error: 没有找到custom-map-result.json！ \033[0m')
        print('\033[1;31m /custom-map/接口数据将为空！ \033[0m!')
    else:
        f.close()

def initHighlightedMap():
    try:
        f = open('./custom-map-high-result.json', 'r')
        data = ""
        lines = f.readlines()
        for line in lines:
            data += line
        global customMapHigh
        customMapHigh = json.dumps(json.loads(data))

        print('\033[1;32m Success: 已加载custom-map-high-result.json! \033[0m')
    except IOError:
        print('\033[1;31m Error: 没有找到custom-map-high-result.json！ \033[0m')
        print('\033[1;31m /custom-map/接口数据将为空！ \033[0m!')
    else:
        f.close()

if __name__ == "__main__":
    initCustomMap()
    initHighlightedMap()
    app.run("0.0.0.0", 5000)
